package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket clientSocket = null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        clientSocket = new Socket(serverIp,serverPort);
    }

    public void start() {
        System.out.println("客户端启动!");
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetWork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true) {
                System.out.print("->");
                if(!scannerConsole.hasNext()) {
                    break;
                }
                //1.从控制台读取数据
                String request = scannerConsole.next();
                //2.把请求发送给服务器
                writer.println(request);
                writer.flush();
                //3.通过服务器读取响应
                String response = scannerNetWork.next();
                //4.输出
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
